package xnj.lazydog.btcontroller.ControlViews.ControlViews;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

import xnj.lazydog.btcontroller.ControlViews.ControlView;
import xnj.lazydog.btcontroller.ControlViews.ViewOptions;
import xnj.lazydog.btcontroller.R;

public class ControlValueButton extends ControlElement {


    Bitmap plus_raw,minus_raw;
    Bitmap plus,minus;


    DecimalFormat decimalFormat;

    public ControlValueButton(ViewOptions options) {
        super(options);
        decimalFormat = new DecimalFormat("##.####");
        plus_raw = BitmapFactory.decodeResource(ControlView.resources, R.drawable.plus);
        minus_raw = BitmapFactory.decodeResource(ControlView.resources, R.drawable.minus);
    }



    float MIN_WH_RATIO = 4;

    float TEXT_RATIO = 0.3f;
    float BMP_RATIO = 0.9f;


    float bmp_pix;
    float real_w,real_h;

    float bmp_offset_x;
    float radius;
    float edge;
    float text_height;
    float label_off_y;
    float text_off_y;

    float last_text_height;

    float left_r,right_r;

    @Override
    public void onSizeChanged() {

        if(w_pix<h_pix*MIN_WH_RATIO)
        {
            real_w = w_pix;
            real_h = w_pix/MIN_WH_RATIO;
        }
        else
        {
            real_w = w_pix;
            real_h = h_pix;
        }


        edge = (real_h)*0.05f;

        radius = real_h*0.2f;

        label_off_y = real_h*0.2f;

        text_height = real_h*TEXT_RATIO;
        if(text_height>max_text_pix)
            text_height = max_text_pix;
        if(Math.abs(text_height-last_text_height)>5) {
            text_off_y = text_height * 0.366f;
            p.setTextSize(text_height);
            last_text_height = text_height;
        }

        rectF.left = -(real_w-real_h*2)*0.5f;
        rectF.right = -rectF.left;
        rectF.bottom = real_h*0.5f;
        rectF.top = -rectF.bottom;

        bmp_pix = BMP_RATIO*real_h;
        bmp_offset_x = (real_w-real_h)*0.5f;

        left_r = real_h/w_pix;
        right_r = 1-left_r;

        plus = Bitmap.createScaledBitmap(plus_raw,(int)bmp_pix,(int)bmp_pix,true);
        minus = Bitmap.createScaledBitmap(minus_raw,(int)bmp_pix,(int)bmp_pix,true);

    }


    float plus_scale=1,plus_scale_d=1,p_dt;
    float minus_scale=1,minus_scale_d=1,m_dt;


    @Override
    public void draw(Canvas canvas) {

        //Path path = new Path();

        p.setColor(THEME_WHITE);
        p.setStyle(Paint.Style.FILL);
        canvas.save();
        canvas.clipRect(rectF);

        canvas.drawRoundRect(rectF,radius,radius,p);

        p.setColor(THEME_TEXT_DARK_COLOR);

        if(linkedValues[0]!=null) {

            canvas.drawText(valuesName[0],0,text_off_y-label_off_y,p);
            if(linkedValues[0].type>0)
                canvas.drawText(decimalFormat.format(linkedValues[0].getFloat()),0,text_off_y+label_off_y,p);
           else
                canvas.drawText(""+linkedValues[0].get(),0,text_off_y+label_off_y,p);
        }else
        {
            canvas.drawText("可编辑",0,text_off_y-label_off_y,p);
            canvas.drawText("文本",0,text_off_y+label_off_y,p);
        }

        canvas.restore();


        m_dt = minus_scale-minus_scale_d;

        if(Math.abs(m_dt)>0.01f)
        {
            minus_scale_d+=m_dt*0.32f;
        }else {
            minus_scale_d = minus_scale;
        }
        p_dt = plus_scale-plus_scale_d;

        if(Math.abs(p_dt)>0.01f)
        {
            plus_scale_d+=p_dt*0.32f;
        }else {
            plus_scale_d = plus_scale;
        }

        canvas.save();
        canvas.translate(-bmp_offset_x,0);
        canvas.scale(minus_scale_d,minus_scale_d);
        canvas.drawBitmap(minus,-bmp_pix*0.5f,-bmp_pix*0.5f,p);
        canvas.restore();

        canvas.save();
        canvas.translate(bmp_offset_x,0);
        canvas.scale(plus_scale_d,plus_scale_d);
        canvas.drawBitmap(plus,-bmp_pix*0.5f,-bmp_pix*0.5f,p);
        canvas.restore();

        p.setStrokeWidth(edge);
        p.setColor(THEME_EDGE);
        p.setStyle(Paint.Style.STROKE);
        canvas.drawRoundRect(rectF,radius,radius,p);
    }

    int s;
    void plus()
    {
        if(linkedValues[0]==null)
            return;
        if(linkedValues[0].type==4)
        {
            linkedValues[0].set(linkedValues[0].getFloat()+options.off_value);
        }else
        {
            s = (int)options.off_value;
            if(s<1)
                s = 1;
            linkedValues[0].set(linkedValues[0].getFloat()+s);
        }
        triggerDataEvent();
    }

    void minus()
    {
        if(linkedValues[0]==null)
            return;
        if(linkedValues[0].type==4)
        {
            linkedValues[0].set(linkedValues[0].getFloat()-options.off_value);
        }else
        {
            s = (int)options.off_value;
            if(s<1)
                s = 1;
            linkedValues[0].set(linkedValues[0].getFloat()-s);
        }
        triggerDataEvent();
    }

    @Override
    public void clicked(Context context) {

        if(rx<left_r)
        {
            minus();
            Thread thread = new Thread()
            {
                @Override
                public void run() {
                    minus_scale = 0.8f;
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    minus_scale = 1;
                }
            };
            thread.start();
        }else if(rx<right_r)
        {

            showEditDialog(context,false);

        }else
        {
            plus();
            Thread thread = new Thread()
            {
                @Override
                public void run() {
                    plus_scale = 0.8f;
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    plus_scale = 1;
                }
            };
            thread.start();
        }
    }


    @Override
    public void showSettingsDialog(Context context) {

        showEditDialog(context,true);

    }

    private static final String TAG = "ControlValueButton";


    void showEditDialog(final Context context, final boolean only_step)
    {

        if (linkedValues[0] == null) {
            Toast.makeText(context, "请先链接一个变量", Toast.LENGTH_SHORT).show();
            return;
        }

        Button cancel,confirm;
        final EditText editText,step;

        TextView edttxt;
        View view = LayoutInflater.from(context).inflate(R.layout.toy_value_button,null);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(view);
        final AlertDialog dialog = builder.create();

        if(dialog.getWindow()!=null)
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        step = view.findViewById(R.id.toy_edit_step);

        editText = view.findViewById(R.id.toy_edit_text);
        edttxt = view.findViewById(R.id.value_info2);

        String v;

        if(linkedValues[0].type==4)
        v = "" + linkedValues[0].getFloat();
                else
        v = "" + linkedValues[0].getInt();

        editText.setText(v);

        if(linkedValues[0].type==4)
            v = ""+options.off_value;
        else
            v = ""+(int)options.off_value;

        step.setText(v);

        if(only_step)
        {
            editText.setVisibility(View.GONE);
            edttxt.setVisibility(View.GONE);
        }

        cancel = view.findViewById(R.id.toy_edit_cancel_button);
        confirm = view.findViewById(R.id.toy_edit_confirm_button);

        initLimitedEdit(editText,null, linkedValues[0].type);
        initLimitedEdit(step,0,MAX_VALUES[linkedValues[0].type],linkedValues[0].type);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                float number;
                float max = MAX_VALUES[linkedValues[0].type];

                float min = MIN_VALUES[linkedValues[0].type];

                try {
                    number = Float.parseFloat(editText.getText().toString());
                }catch (NumberFormatException e)
                {
                    number = 0;
                    editText.setText("0");
                }
                if(number>max)
                {
                    String str = ""+max;
                    editText.setText(str);
                    number = max;
                }
                if(number<min)
                {
                    String str = ""+min;
                    editText.setText(str);
                    number = min;
                }

                //Log.w(TAG, "onClick: "+data_dir_tx[0]);
                if(!data_dir_tx[0])
                    Toast.makeText(context,"该控件链接的是接收组变量，因此编辑无效",Toast.LENGTH_SHORT).show();
                else {
                 if(!only_step)
                    linkedValues[0].set(number);
                }
                try {
                    number = Float.parseFloat(step.getText().toString());
                }catch (NumberFormatException e)
                {
                    number = 0;
                    step.setText("0");
                }
                if(number>max)
                {
                    String str = ""+max;
                    step.setText(str);
                    number = max;
                }
                if(number<min)
                {
                    String str = ""+min;
                    step.setText(str);
                    number = min;
                }

                options.off_value = number;
                if(!only_step)
                    triggerDataEvent();
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    float f_rx;
    float f_value;

    @Override
    public void dragged() {
        if(isPressed&&linkedValues[0]!=null)
        {
            linkedValues[0].set(f_value+(rx-f_rx)*options.off_value);
        }
    }

    @Override
    public void released() {
    }
    @Override
    public void pressed() {
        if(linkedValues[0]!=null) {
            f_rx = rx;
            f_value = linkedValues[0].getFloat();
        }
    }
    @Override
    public void zoomed(float sx, float sy) {
    }
}
